package com.xxwy.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
 * HttpObject 客户端和服务器端相互通信的数据被封装为HttpObject
 *
 * @author wy
 * @date 2020/3/5 11:24
 */
public class HttpHandler extends SimpleChannelInboundHandler<HttpObject> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    if (msg instanceof HttpRequest) {
      System.out.println("msg class :" + msg.getClass());
      System.out.println("client address: " + ctx.channel().remoteAddress());

      //只对url响应
      HttpRequest request = (HttpRequest) msg;
      URI uri = new URI(request.uri());
      if("/favicon.ico".equals(uri.getPath())) {
        System.out.println("请求了 favicon.ico, 不做响应");
        return;
      }

      ByteBuf byteBuf = Unpooled.copiedBuffer("hello I'm server", CharsetUtil.UTF_8);
      DefaultFullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
      fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
      fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

      //将构建好得response返回
      ctx.writeAndFlush(fullHttpResponse);

    }
  }
}
